<?php

namespace app\admin\jobs;

use app\admin\model\Algorithm;
use think\facade\Db;
use app\api\service\Common;
use think\facade\Lang;
use think\facade\Log;

class InitTranslation
{
    // 终端命令： php think queue initTranslation   
    protected $languageCode;
    protected $commonService;

    // 定义翻译配置
    private const TRANSLATE_CONFIG = [
        'product_merge' => [
            'table' => 'product_merge',
            'name_field' => 'productname,describe',
            'order' => 'create_time desc ,update_time desc'
        ],
        'product' => [
            'table' => 'product',
            'name_field' => 'cname,abbr',
            'order' => 'create_time desc ,update_time desc'
        ],
        'product_brand' => [
            'table' => 'product_brand',
            'name_field' => 'name,description',
            'order' => 'create_time desc ,update_time desc'
        ],
        'product_category' => [
            'table' => 'product_category',
            'name_field' => 'name,description',
            'order' => 'create_time desc ,update_time desc'
        ],
        'product_currency' => [
            'table' => 'product_currency',
            'name_field' => 'name,name_short',
            'order' => 'create_time desc ,update_time desc'
        ],
        'warehouse' => [
            'table' => 'warehouse',
            'name_field' => 'show_name',
            'order' => 'create_time desc ,update_time desc'
        ],
    ];

    public function __construct()
    {
        $this->commonService = new Common();
        $this->languageCode = array_filter(array_keys($this->commonService::LANGUAGE_CODE), function ($code) {
            return $code !== 'en';
        });
    }

    /**
     * 初始化翻译
     * @param $data
     * @return bool
     */
    public function translation()
    {
        // 将任务分配给多个进程
        foreach ($this->languageCode as $type => $lang) {
            $this->startAsyncTask($lang);
        }
    }

    /**
     * 启动异步任务
     * @param string $lang 语言信息
     */
    private function startAsyncTask(string $lang)
    {
        // 确保日志目录存在
        $logDir = runtime_path() . 'cli_logs';
        if (!is_dir($logDir)) {
            if (!mkdir($logDir, 0755, true)) {
                throw new \RuntimeException('无法创建日志目录: ' . $logDir);
            }
        }

        $logFile = $logDir . '/initTranslation_' . date('Y-m-d') . '.log';

        // 确保日志文件存在并可写
        if (!file_exists($logFile)) {
            if (!touch($logFile)) {
                throw new \RuntimeException('无法创建日志文件: ' . $logFile);
            }
            chmod($logFile, 0644);
        }

        if (!is_writable($logFile)) {
            throw new \RuntimeException('日志文件不可写: ' . $logFile);
        }

        $command = sprintf(
            'php think queue initTranslation --lang=%s >> "%s" 2>&1 & echo "$(TZ=\'Asia/Shanghai\' date \'+%%Y-%%m-%%d %%H:%%M:%%S\') Command executed for lang: %s" >> "%s" 2>&1 &',
            $lang,
            $logFile,
            $lang,
            $logFile
        );
        exec($command);
    }

    /**
     * 处理翻译
     * @param string $lang 语言代码
     */
    public function handleTranslation(string $lang)
    {
        try {

            // 处理common
            $this->handleCommonTranslation($lang);

            // 处理算法翻译
            $this->handleAlgorithmTranslation($lang);

            // 处理配置项翻译
            $this->handleConfigTranslation($lang);

            echo '[' . date('Y-m-d H:i:s') . '] Translation End, Lang: ' . $lang . PHP_EOL;
        } catch (\Exception $e) {
            Log::error('Translation process failed: ' . $e->getMessage());
            throw $e;
        }
    }

    /**
     * 处理算法相关翻译
     * @param string $lang 语言代码
     */
    private function handleAlgorithmTranslation(string $lang)
    {
        $algorithm = new Algorithm();
        $algorithmData = $algorithm->getAttributes('algorithm');

        foreach ($algorithmData as $value) {
            $this->translateAndLog($value, $lang, 'algorithm');
        }
    }



    /**
     * 处理common相关翻译
     * @param string $lang 语言代码
     */
    private function handleCommonTranslation(string $lang)
    {
        $commonArray = [
            'orderStatus' => [
                'All',
                'Pending Payment',
                'In Review',
                'Pending Shipment',
                'Pending Receipt',
                'Cancelled',
                'Completed',
                'Paid',
                'Shipped',
                'Partial Shipment'
            ],
            'productSpeckeys' => [
                'Product Name',
                'Also known as',
                'Brand',
                'Model/Color',
                'Condition',
                'Warranty',
                'RAM',
                'Chip Number',
                'Working Mode',
                'Power Consumption',
                'Input Voltage',
                'Noise level',
                'Network Connection Mode',
                'Operation Temperature',
                'Operation Humidity',
                'Cooling Way',
                'Net Weight',
                'Gross Weight',
                'Net Dimensions',
                'Package Dimensions',
                'PSU included',
                'Power Cord included',
                'Power Cord Specification',
                'Power Cord/Plug Standard',
                'Free Shipping',
                'Magnets included',
                'Battery included',
            ],
            'powerline_standards'=>[
                'CN - Power Cord',
                'USA - Power Cord',
                'EURO - Power Cord',
                'UK - Power Cord',
                'Other'
            ],
            'other'=>[
                'Self Pickup',
                'Express Delivery',
                'Crypto Pay',
                'Wire Transfer',
                'In Stock',
                'Available on backorder',
                'Future',
                'Destination Warehouse',
                'Spot',
                'English',
                'French',
                'German',
                'Italian',
                'Spanish',
                'Portuguese',
                'Russian',
                'Dutch',
                'Arabic',
                'Chinese',
                'Indonesian',
                'Vietnamese',
                'Japanese',
                'Korean',
                'Bengali',
                'Hindi',
                'Urdu',

            ]
        ];

        foreach ($commonArray as $key => $value) {
            foreach ($value as $v) {
                $this->translateAndLog($v, $lang, $key);
            }
        }
    }

    /**
     * 处理配置项翻译
     * @param string $lang 语言代码
     */
    private function handleConfigTranslation(string $lang)
    {
        foreach (self::TRANSLATE_CONFIG as $type => $config) {
            $items = Db::name($config['table'])
                ->where('is_del', 0)
                ->field("id,{$config['name_field']}")
                ->order($config['order'])
                ->select()
                ->toArray();

            foreach ($items as $item) {
                $field = explode(',', $config['name_field']);

                foreach ($field as  $value) {
                    if (isset($item[$value]) && $item[$value]) {
                        $this->translateAndLog($item[$value], $lang, $type);
                    } else {
                        echo '[' . date('Y-m-d H:i:s') . '] Translation failed : for type ' . $type . ', lang: ' . $lang . ', Result: field not exist config: ' . json_encode($config, JSON_UNESCAPED_UNICODE)  . 'item: ' . json_encode($item, JSON_UNESCAPED_UNICODE) . PHP_EOL;
                    }
                }
            }
        }
    }


    /**
     * 执行翻译并记录日志
     * @param string $content 需要翻译的内容
     * @param string $lang 目标语言
     * @param string $type 翻译类型
     */
    private function translateAndLog(string $content, string $lang, string $type)
    {
        $translateData = [
            'content' => json_encode([md5($content) => $content]),
            'target_language' => $lang
        ];

        try {
            $translate = $this->commonService->translateForScript($translateData);
            // 记录翻译结果
            if( 0 != $translate['code']){
                echo '[' . date('Y-m-d H:i:s') . '] Translation failed : for type ' . $type . ', lang: ' . $lang . ', Result: ' . json_encode($translate, JSON_UNESCAPED_UNICODE) . 'Params: ' . json_encode($translateData, JSON_UNESCAPED_UNICODE) . PHP_EOL;
            }
            // 添加延迟以避免请求过于频繁
            usleep(50000);
        } catch (\Exception $e) {
            Log::error("Translation failed for type {$type}: " . $e->getMessage());
            throw $e;
        }
    }
}
